package com.budwk.app.util;

import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.xmlbeans.XmlCursor;

public class ExcelDeleteImage {

    public static void deleteCTAnchor(XSSFPicture xssfPicture) {
        XSSFDrawing drawing = xssfPicture.getDrawing();
        XmlCursor cursor = xssfPicture.getCTPicture().newCursor();
        cursor.toParent();
        if (cursor.getObject() instanceof org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor) {
            for (int i = 0; i < drawing.getCTDrawing().getTwoCellAnchorList().size(); i++) {
                if (cursor.getObject().equals(drawing.getCTDrawing().getTwoCellAnchorArray(i))) {
                    drawing.getCTDrawing().removeTwoCellAnchor(i);
                }
            }
        } else if (cursor.getObject() instanceof org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTOneCellAnchor) {
            for (int i = 0; i < drawing.getCTDrawing().getOneCellAnchorList().size(); i++) {
                if (cursor.getObject().equals(drawing.getCTDrawing().getOneCellAnchorArray(i))) {
                    drawing.getCTDrawing().removeOneCellAnchor(i);
                }
            }
        } else if (cursor.getObject() instanceof org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTAbsoluteAnchor) {
            for (int i = 0; i < drawing.getCTDrawing().getAbsoluteAnchorList().size(); i++) {
                if (cursor.getObject().equals(drawing.getCTDrawing().getAbsoluteAnchorArray(i))) {
                    drawing.getCTDrawing().removeAbsoluteAnchor(i);
                }
            }
        }
    }

    public static void deleteEmbeddedXSSFPicture(XSSFPicture xssfPicture) {
        if (xssfPicture.getCTPicture().getBlipFill() != null) {
            if (xssfPicture.getCTPicture().getBlipFill().getBlip() != null) {
                if (xssfPicture.getCTPicture().getBlipFill().getBlip().getEmbed() != null) {
                    String rId = xssfPicture.getCTPicture().getBlipFill().getBlip().getEmbed();
                    XSSFDrawing drawing = xssfPicture.getDrawing();
                    drawing.getPackagePart().removeRelationship(rId);
                    drawing.getPackagePart().getPackage().deletePartRecursive(drawing.getRelationById(rId).getPackagePart().getPartName());
                }
            }
        }
    }

    public static void deleteHSSFShape(HSSFShape shape) {
        HSSFPatriarch drawing = shape.getPatriarch();
        drawing.removeShape(shape);
    }
}